package com.tang.watermake;

import com.tang.bean.WaterSensor;
import com.tang.functions.WaterSensorMapFunction;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * 乱序流内置水位线
 * 1、都是周期性生成的： 默认200ms
 * 2、有序流：  watermark = 当前最大的事件时间 - 1ms
 * 3、乱序流：  watermark = 当前最大的事件时间 - 延迟时间 - 1ms
 *
 * @author tang
 * @since 2023/6/12 15:34
 */
public class WatermarkOutOfOrdernessDemo {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        /*
         * 演示watermark多并行度下的传递
         * 1、接收到上游多个，取最小
         * 2、往下游多个发送， 广播
         */
        env.setParallelism(2); // 在ENV设置的总算子
        // 自定义Watermark生成周期
        //env.getConfig().setAutoWatermarkInterval(1000);

        SingleOutputStreamOperator<WaterSensor> map = env.socketTextStream("192.168.70.141", 7777)
                .map(new WaterSensorMapFunction());

        
        
        // 1.定义Watermark策略
        WatermarkStrategy<WaterSensor> watermarkStrategy = WatermarkStrategy
                // 1.1 指定watermark生成：乱序的watermark，等待3S时间
                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3L))
                // 1.2 指定时间戳分配器，从数据中提取
                .withTimestampAssigner((element, recordTimestamp) -> {
                    // 返回的时间戳是毫秒
                    System.out.println("数据= " + element + "，recordTs=" + recordTimestamp);
                    return element.getTs() * 1000L;
                });

        // 2. 指定watermark策略
        SingleOutputStreamOperator<WaterSensor> sourceWithWatermark = map
                .assignTimestampsAndWatermarks(watermarkStrategy);
        sourceWithWatermark.keyBy(WaterSensor::getId)
                // 3. 使用事件时间语义的窗口
                .window(TumblingEventTimeWindows.of(Time.seconds(10)))
                .process(new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>() {
                    @Override
                    public void process(String s, ProcessWindowFunction<WaterSensor, String, String, TimeWindow>.Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                        long startTs = context.window().getStart();
                        long endTs = context.window().getEnd();
                        String windowStart = DateFormatUtils.format(startTs, "yyyy-MM-dd HH:mm:ss.SSS");
                        String windowEnd = DateFormatUtils.format(endTs, "yyyy-MM-dd HH:mm:ss.SSS");

                        long count = elements.spliterator().estimateSize();

                        out.collect("key=" + s + "的窗口[" + windowStart + "," + windowEnd + ")包含" + count + "条数据===>" + elements);
                    }
                }).print();

        env.execute();
    }

}
